package com.shopping.service.impl;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shopping.dao.Impl.CartsDao;
import com.shopping.model.Carts;


@Service
public class CartsService {

	@Autowired
	private CartsDao cartsDao;
	
	@Autowired
	private GoodsServiceImpl goodsService;
	
	public int getCount(int userId) {
		return cartsDao.selectSumAmountByUserId(userId);
	}

	/**
	 * 加入购物车
	 * @param goodId 商品ID
	 * @param userId 用户ID
	 * @return 加入成功返回true，加入失败返回false
	 */
	public boolean save(int goodId, int userId) {
		return cartsDao.save(goodId, userId);
	}

	public List<Carts> getList(int userId) {
		return pack(cartsDao.selectListByUserId(userId));
	}
	
	/**
	 *  计算总价格
	 * @param id
	 * @return
	 */
	public long getTotal(int userId) {
		int total = 0;
		List<Carts> cartList = this.getList(userId);
		if(Objects.nonNull(cartList) && ! cartList.isEmpty()) {
			for(Carts cart : cartList) {
				total += cart.getGood().getPrice() * cart.getAmount();
			}
		}
		return total;
	}

	
	
	/**
	 * 封装
	 * @param list
	 * @return
	 */
	private List<Carts> pack(List<Carts> list) {
		for(Carts cart : list) {
			cart = pack(cart);
		}
		return list;
	}

	private Carts pack(Carts cart) {
		if(Objects.nonNull(cart)) {
			cart.setGood(goodsService.findById(cart.getGoodId()));
			cart.setTotal(cart.getAmount() * cart.getGood().getPrice());
		}
		return cart;
	}

	
	/**
	 * 清空某个客户的购物车
	 * @param userId
	 */
	public void clean(int userId) {
		cartsDao.deleteByUserId(userId);
	}

	
}
